package com.zc.listener;

import com.zc.entity.OrderEnity;
import com.zc.enums.OrderStatusChangeEventEnum;
import com.zc.enums.OrderStatusEnum;
import com.zc.handler.PersistStateMachineHandler;
import com.zc.repository.OrderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.statemachine.StateMachine;
import org.springframework.statemachine.state.State;
import org.springframework.statemachine.transition.Transition;

/**
 * @author : ville
 * @version : 1.0.0
 * @description : 持久化状态发生变化的订单实体的Listener
 * @createTime : 2020/6/9-17:24
 * @copyright : villebo@126.com
 * @modify : ville
 **/
public class OrderPersistStateChangeListener implements PersistStateMachineHandler.PersistStateChangeListener {

    @Autowired
    private OrderRepository orderRepository;
    /**
     * 当状态被持久化，调用此方法
     *
     * @param state
     * @param message
     * @param transition
     * @param stateMachine 状态机实例
     */
    @Override
    public void onPersist(State<OrderStatusEnum, OrderStatusChangeEventEnum> state, Message<OrderStatusChangeEventEnum> message, Transition<OrderStatusEnum, OrderStatusChangeEventEnum> transition, StateMachine<OrderStatusEnum, OrderStatusChangeEventEnum> stateMachine) {
        if (message != null && message.getHeaders().containsKey("order")) {
            Integer  order = message.getHeaders().get("order", Integer.class);
            OrderEnity o = orderRepository.findByOrderId(order);
            OrderStatusEnum status = state.getId();
            o.setStatus(status);
            orderRepository.save(o);
        }
    }
}
